#include "common.h"

static int msgid1;
static int msgid2;

void destory()
{
	printf("server is closing !\n");
	if(msgctl(msgid1 , IPC_RMID , NULL) == -1)
		perror("close queue 1 failed") , exit(-1);
	if(msgctl(msgid2 , IPC_RMID , NULL) == -1)
		perror("close queue 2 failed") , exit(-1);
	printf("server has been closed !\n");
	exit(0);
}

void init()
{
	if((msgid1 = msgget(key1,IPC_CREAT | IPC_EXCL |0660)) == -1)
	{
		perror("queue 1 failed!") , exit(-1);
	}
	else
	{
		printf("queue 1 was created!\n");
	}
	if((msgid2 = msgget(key2,IPC_CREAT | IPC_EXCL |0660)) == -1)
	{
		perror("queue 2 failed!") , exit(-1);
	}
	else
	{
		printf("queue 2 was created!\n");
	}
}

void start()
{
	printf("server starts to run !\n");
	
	sleep(1);
	pid_t pid = vfork();
	
	if(pid == -1)
	{
		printf("creating child process failed");
	}
	
	else if(pid == 0)
	{
		execl("./start",NULL);
	}
	else
		waitpid(pid,0,0);
}

//server
void main()
{
	signal(SIGINT,destory);
	init();		//create the 2 queues
	start();	//start to run the server
}
